<template>
  <div>
    <div style="padding-top: 50px">
      <h1>滑块验证码登录 Demo</h1>
      <table style="margin: auto;">
        <tr>
          <td>登录名：</td>
          <td>
            <input type="text" v-model="username" />
          </td>
        </tr>
        <tr>
          <td>密码：</td>
          <td>
            <input type="password" v-model="password" />
          </td>
        </tr>
      </table>
      <div style="padding: 5px">
        <input type="button" value="登录" @click="onClickLogin" />
      </div>
    </div>
    <transition name="fade">
      <slide-validation
        ref="captcha"
        v-if="show"
        :show="show"
        :router="router"
        :register="registerCaptcha"
        :login="loginCaptcha"
        @close="onCloseCaptcha"
      ></slide-validation>
    </transition>
  </div>
</template>

<script>
const Validation = () => import("@/components/Validation"); //滑块验证码
import { check, register } from "@/api/index.js";

export default {
  name: "Login",
  components: { "slide-validation": Validation },

  data() {
    return {
      username: "",
      password: "",
      show: false,
      router: "/home",
    };
  },

  methods: {
    /**
     * 点击登录按钮
     */
    onClickLogin() {
      this.show = true;
    },

    /**
     * 注册验证码
     */
    registerCaptcha() {
      return new Promise((resolve, reject) => {
        register()
          .then((resp) => {
            resolve(resp.data);
          })
          .catch((err) => {
            reject(err);
          });
      });
    },

    /**
     * 拼图校验与登录
     */
    loginCaptcha(sliceX) {
      return new Promise((resolve, reject) => {
        let form = {
          username: this.username,
          password: this.password,
          sliceX: sliceX,
        };
        check(form).then(
          (resp) => {
            resolve(resp.data);
          },
          (err) => {
            reject(err);
          }
        );
      });
    },

    /**
     * 关闭弹出验证码
     */
    onCloseCaptcha() {
      this.show = false;
    },
  },
};
</script>

<style scoped>
table tr td {
  padding: 5px;
}

table tr td:first-child {
  text-align: right;
}

table tr td:last-child {
  text-align: left;
}

/* .fade-enter-active,
.fade-leave-active {
  transition: opacity 0.4s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
} */
</style>
